package com.wefans.wefansapp.activity;

import java.util.Hashtable;
import java.util.Set;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wefans.wefansapp.R;
import com.wefans.wefansapp.common.tool.data.MFDataManager;
import com.wefans.wefansapp.common.tool.data.ResDefaultData;
import com.wefans.wefansapp.common.tool.data.ResGetCountry;
import com.wefans.wefansapp.common.tool.debug.MFDebug;
import com.wefans.wefansapp.common.tool.network.MFNetworkManager;
import com.wefans.wefansapp.common.tool.network.MFNetworkManager.IOnNetworkListener;
import com.wefans.wefansapp.common.tool.network.model.NetJsonData;
import com.wefans.wefansapp.common.tool.network.model.NetMessage;
import com.wefans.wefansapp.common.tool.utils.MFCountryCodeUtil;
import com.wefans.wefansapp.common.tool.utils.MFToastUtil;

public class JoinActivity extends BaseActivity {

	private static int REQUEST_MYSTAR = 100;
	
	private Context mContext = null;
	private boolean bValidEmail = false;
	private boolean bValidNickname = false;
	private boolean bValidRecommender = false;
	
	private EditText mEtEmail = null;
	private EditText mEtPw1 = null;
	private EditText mEtPw2 = null;
	private EditText mEtName = null;
	private EditText mEtNickname = null;
	private TextView mTvCountry = null;
	private LinearLayout mLlCountrySelector = null;
	private EditText mEtPhoneNumber = null;
	private EditText mEtRecommender = null;
	private TextView mTvTerms = null;
	private Button mBtnNext = null;
	
	private String mStrEmail = "";
	private String mStrName = "";
	private String mStrNickname = "";
	private String mStrPassword1 = "";
	private String mStrPassword2 = "";
	private String mStrCountry = "";
	private String mStrPhoneNum = "";
	private String mStrRecommender = "";
	
	private String mCountryItems[] = null;
	private Hashtable<String, String> mapCountry = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		mContext = this;
		
		setContentView(R.layout.activity_join);
		
		mEtEmail = (EditText)findViewById(R.id.ET_EMAIL);
		mEtPw1 = (EditText)findViewById(R.id.ET_PASSWORD);
		mEtPw2 = (EditText)findViewById(R.id.ET_PASSWORD_CONFIRM);
		mEtName = (EditText)findViewById(R.id.ET_NAME);
		mEtNickname = (EditText)findViewById(R.id.ET_NICKNAME);
		mTvCountry = (TextView)findViewById(R.id.TV_COUNTRY);
		mLlCountrySelector = (LinearLayout)findViewById(R.id.LL_COUNTRY_SELECT);
		mEtPhoneNumber = (EditText)findViewById(R.id.ET_PHONENUM);
		mEtRecommender = (EditText)findViewById(R.id.ET_RECOMMENDER);
		mTvTerms = (TextView)findViewById(R.id.TV_TERMS);
		mBtnNext = (Button)findViewById(R.id.BTN_NEXT);
		
		mLlCountrySelector.setOnClickListener(mClickListener);
		mTvTerms.setOnClickListener(mClickListener);
		mBtnNext.setOnClickListener(mClickListener);
	}
	
	OnClickListener mClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.LL_COUNTRY_SELECT:
				
				final String strItems[] = MFCountryCodeUtil.getValueList(mContext);
				AlertDialog.Builder ab = new AlertDialog.Builder(JoinActivity.this);
			    ab.setTitle(getString(R.string.country));
				ab.setSingleChoiceItems(strItems, 0,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								mTvCountry.setText(strItems[whichButton]);
								dialog.cancel();
							}
						});						
				ab.show();
				break;
			case R.id.BTN_NEXT:
				checkData();
				break;
			case R.id.TV_TERMS:
				showterms();
				break;
			}
		}
	};
	
	private void showterms() {
		Intent intent = new Intent(JoinActivity.this, TermsActivity.class);
		startActivity(intent);
	}
	
	private void checkData() {
		
		mStrEmail = mEtEmail.getText().toString();
		mStrName = mEtName.getText().toString();
		mStrNickname = mEtNickname.getText().toString();
		mStrPassword1 = mEtPw1.getText().toString();
		mStrPassword2 = mEtPw2.getText().toString();
		mStrCountry = MFCountryCodeUtil.getCodeByValue(mContext, mTvCountry.getText().toString());
		mStrPhoneNum = mEtPhoneNumber.getText().toString();
		mStrRecommender = mEtRecommender.getText().toString();
		
		if (mStrEmail == null || mStrEmail.length() <= 0 ||
			mStrName == null || mStrName.length() <= 0 ||
			mStrNickname == null || mStrNickname.length() <= 0 ||
			mStrPassword1 == null || mStrPassword1.length() <= 0 ||
			mStrPassword2 == null || mStrPassword2.length() <= 0 ||
			mStrCountry == null || mStrCountry.length() <= 0 ||
			mStrPhoneNum == null || mStrPhoneNum.length() <= 0) {
			return;
		}
		
		findViewById(R.id.TV_CHECK_PASSWORD_OK).setVisibility(mStrPassword1.equals(mStrPassword2) ? View.VISIBLE : View.GONE);
		findViewById(R.id.TV_CHECK_PASSWORD_CANCEL).setVisibility(mStrPassword1.equals(mStrPassword2) ? View.GONE : View.VISIBLE);
		
		if (mStrPassword1.equals(mStrPassword2) == false) {
			return;
		}
		
		requestCheckEmail();
	}
	
	private void requestCheckEmail() {
		String strUrl = MFNetworkManager.BASE_URL + "/user/get_email_check.php";
		strUrl = strUrl + "?email=" + mStrEmail;
		MFNetworkManager.getInstance(this).requestGetData(MFNetworkManager.REQUEST_CHECK_EMAIL, strUrl, mNetworkListener);
	}
	
	private void requestCheckNickname() {
		String strUrl = MFNetworkManager.BASE_URL + "/user/get_nickname_check.php";
		strUrl = strUrl + "?nickname=" + mStrNickname;
		MFNetworkManager.getInstance(this).requestGetData(MFNetworkManager.REQUEST_CHECK_NICKNAME, strUrl, mNetworkListener);
	}
	
	private void requestCheckRecommender() {
		String strUrl = MFNetworkManager.BASE_URL + "/user/get_recommend_check.php";
		strUrl = strUrl + "?recommend=" + mStrRecommender;
		MFNetworkManager.getInstance(this).requestGetData(MFNetworkManager.REQUEST_CHECK_RECOMMENDER, strUrl, mNetworkListener);
	}
	
	IOnNetworkListener mNetworkListener = new IOnNetworkListener() {
		
		@Override
		public void onNetMessage(int resultCode, NetMessage message) {
			try {
	            //서버 여동 데이터
	            if( message instanceof NetJsonData ) {
	                long magicNum = ((NetJsonData) message).getMagicNum();
	                String json = ((NetJsonData) message).getResponseJson();
	                
	                if( json == null ) {
	                    throw new Exception("invalid json data");
	                }
	                
	                Gson gson = new Gson();
	                
	                ResDefaultData resultData = (ResDefaultData)gson.fromJson(json, ResDefaultData.class);
                    if( resultData == null ) {
                        throw new Exception("Gson parsing error");
                    }
	                
	                if (magicNum == MFNetworkManager.REQUEST_CHECK_EMAIL) {
	                	
	                	findViewById(R.id.TV_CHECK_EMAIL_OK).setVisibility(resultData.isSuccsess() ? View.VISIBLE : View.GONE);
	            		findViewById(R.id.TV_CHECK_EMAIL_CANCEL).setVisibility(resultData.isSuccsess() ? View.GONE : View.VISIBLE);
	            		
	                	if (resultData.isSuccsess()) {
	                		requestCheckNickname();
	                	}
	                } else if (magicNum == MFNetworkManager.REQUEST_CHECK_NICKNAME) {
	                	
	                	findViewById(R.id.TV_CHECK_NICKNAME_OK).setVisibility(resultData.isSuccsess() ? View.VISIBLE : View.GONE);
	            		findViewById(R.id.TV_CHECK_NICKNAME_CANCEL).setVisibility(resultData.isSuccsess() ? View.GONE : View.VISIBLE);
	            		
	                	if (resultData.isSuccsess()) {
	                		if (mStrRecommender != null && mStrRecommender.length() > 0) {
	                			requestCheckRecommender();
	                		} else {
	                			nextStep();
	                		}
	                	}
	                } else if (magicNum == MFNetworkManager.REQUEST_CHECK_RECOMMENDER) {
	                	if (resultData.isSuccsess()) {
	                		nextStep();
	                	} else {
	                		MFToastUtil.NetResponseToast(getApplicationContext(), resultData.getResultcode(), resultData.getResultmsg());
	                	}
	                }
	            }	            
	        } catch(Exception e) {
	            MFDebug.e(e);
	        }		
		}
	};
	
	private void nextStep() {
		Intent intent = new Intent(JoinActivity.this, MystarActivity.class);
		intent.putExtra("country", mStrCountry);
		intent.putExtra("name", mStrName);
		intent.putExtra("nickname", mStrNickname);
		intent.putExtra("email", mStrEmail);
		intent.putExtra("passwd", mStrPassword1);
		intent.putExtra("mobile", mStrPhoneNum);
		intent.putExtra("recommend", mStrRecommender);
		
		intent.putExtra("from", "join");
		startActivityForResult(intent, REQUEST_MYSTAR);
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_MYSTAR) {
			if (resultCode == Activity.RESULT_OK) {
				finish();
			}
		}
	};
}
